var path = require("path"),
    fs = require("fs");

exports.render = function (req, res, viewName, context) {
    var filename = path.join(__dirname, 'views', viewName);

    var t = fs.readFileSync(filename, 'utf-8');

//    if (context && Object.prototype.toString.apply(context) === '[object Object]') {
//        for (var key in context) {
//            eval('var ' + key + ' =' + JSON.stringify(context[key]));
//        }
//    }

//    var output = t.replace(/<%=([^<]+)%>/g, function (a, b) {
//        return eval(b);
//    });

    var output = t.replace(/<%([^<]+)%>/g, function (a, b) {
        return eval('JSON.stringify(context.' + b + ')');
    });

    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(output);
}

exports.renderJson = function (req, res, json) {
    var buf = new Buffer(JSON.stringify(json));
    res.writeHead(200,
        { 'Content-Type': 'application/json; charset=UTF-8',
            'Content-Length': buf.length
        }
    );
    res.end(buf);
}

exports.renderImg = function (req, res, buf) {
    res.writeHead(200,
        {
            'Content-Type': 'image/jpg',
            'Transfer-Encoding': 'chunked'
        });
    res.write(buf, "binary");
    res.end();
}